package dilmaj.client;

import com.google.gwt.user.client.rpc.AsyncCallback;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Panel;

import dilmaj.shared.StarEntryVO;
import dilmaj.shared.StarSuggestionVO;

public class CloseHandler implements ClickHandler {
	private StarPanel owner;
	private StarServiceAsync starSvc = GWT.create(StarService.class);
	
	public CloseHandler(StarPanel owner) {
		this.owner=owner;
	}
	
	AsyncCallback<StarEntryVO> entryCallback=new AsyncCallback<StarEntryVO>() {

		@Override
		public void onFailure(Throwable caught) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onSuccess(StarEntryVO result) {
			// TODO Auto-generated method stub
			//DataStore.installDataStore();
			//owner.getDataVO().getButtonPanel().setTitle(result.getCaption());
			owner.getButtonPanel().getButton().setText(result.getCaption());
			DataStore.hideWait();
		}
		
	};
	
	AsyncCallback<StarEntryVO> suggestionCallback=new AsyncCallback<StarEntryVO>() {

		@Override
		public void onFailure(Throwable caught) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onSuccess(StarEntryVO result) {
			// TODO Auto-generated method stub
			owner.getDataVO().addAttachment(result);
			if (starSvc == null) {
			      starSvc = GWT.create(StarService.class);
			    }
			/*StarSuggestionVO suggestionVO=owner.getSuggestionVO();
			suggestionVO.setCaption(owner.getSuggestionText());*/
			owner.getDataVO().setCaption(owner.getDataCaption());
			DataStore.add(result);
			starSvc.updateEntry(owner.getDataVO(), entryCallback);
			DataStore.hideWait();
		}
	};
	
	@Override
	public void onClick(ClickEvent event) {
		// TODO Auto-generated method stub
		if (starSvc == null) {
		      starSvc = GWT.create(StarService.class);
		    }
		
		StarSuggestionVO suggestionVO=owner.getSuggestionVO();
		if (suggestionVO==null) {
			suggestionVO=new StarSuggestionVO();
			suggestionVO.setCaption(owner.getSuggestionText());
			if (DataStore.getUserid()!=-1) {
				suggestionVO.setUserID(DataStore.getUserid());
				suggestionVO.setUserName(DataStore.getUsername());
			}
			DataStore.showWait();
			starSvc.addEntry(suggestionVO, suggestionCallback);
		} else {
			suggestionVO.setCaption(owner.getSuggestionText());
			owner.getDataVO().setCaption(owner.getDataCaption());
			DataStore.showWait();
			starSvc.updateEntry(owner.getDataVO(), entryCallback);
		}
		
		owner.setVisible(false);
		DataStore.closePanel(owner);
	}

}
